import { service } from '@/apis'
import router from '@/router'
import { useStorage } from '@vueuse/core'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { storage } from '../utils/storage'

// 本地所有缓存
const data = storage.info()
export const useUserStore = defineStore('user', () => {

  const Authorization = useStorage('token', { expire: 0, refreshExpire: 0, refreshToken: '', token: '' })
  // const userInfo = useStorage('userInfo', {})

  const token = ref<string>(data.token);
  const info = ref<any | null>(data.userInfo);

  function setToken(data: { token: string; expire: number; refreshToken: string; refreshExpire: number } = {
    expire: 0,
    refreshExpire: 0,
    refreshToken: '',
    token: ''
  }) {
    token.value = data.token;
    // storage.set('token', data.token, data.expire);
    storage.set('token', data.token);
    // storage.set('refreshToken', data.refreshToken, data.refreshExpire);
  }

  async function getInfo() {
    return service({ path: '/student/student/person', method: 'get' }).then((res) => {
      set(res);
      return res;
    });
  }

  function set(value: any) {
    info.value = value;
    storage.set('userInfo', value);
    // userInfo.value = value
  }

  function clear() {
    storage.remove('userInfo');
    storage.remove('token');
    token.value = '';
    info.value = null;
  }

  async function logout() {
    clear();
    router.push("/stacks/sign-in");
    // pushStack('/sign-in');
  }

  return {
    token,
    info,
    getInfo,
    set,
    clear,
    setToken,
    logout
  };
});

